package com.web.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

final public class UploadUtils {

	// 上传配置
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 内存临界值3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 最大文件上传值40MB
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 最大请求值50MB

	public static List<String> upload(HttpServletRequest request) {
		return upload(request,request.getServletContext().getRealPath("./")+"upload/");
	}

	public static List<String> upload(HttpServletRequest request, String uploadPath) {
		// 检测是否为多媒体上传
		if (!ServletFileUpload.isMultipartContent(request)) {
			throw new RuntimeException("不是为多媒体上传");
		}

		// 配置上传参数
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		// 设置临时存储目录
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		
		ServletFileUpload upload = new ServletFileUpload(factory);

		// 设置最大文件上传值
		upload.setFileSizeMax(MAX_FILE_SIZE);

		// 设置最大请求值 (包含文件和表单数据)
		upload.setSizeMax(MAX_REQUEST_SIZE);

		// 中文处理
		upload.setHeaderEncoding("UTF-8");

		// 如果目录不存在则创建
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}

		List<String> filePaths = new ArrayList<>();
		try {
			// 解析请求的内容提取文件数据
			List<FileItem> formItems = upload.parseRequest(new ServletRequestContext(request));

			if (formItems != null && formItems.size() > 0) {
				// 迭代表单数据
				for (FileItem item : formItems) {
					// 处理不在表单中的字段
					if (!item.isFormField()) {
						String uuid = UUID.randomUUID().toString().replace("-", "")+"_";
						String fileName = uuid + item.getName();
						String filePath = uploadPath + fileName;
						File storeFile = new File(filePath);
						// 在控制台输出文件的上传路径
						System.out.println(filePath);
						filePaths.add(fileName);
						// 保存文件到硬盘
						item.write(storeFile);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return filePaths;
	}
}
